package com.bdqn.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.mapper.UserMapper;
import com.bdqn.mybatis.ServiceImpl;
import com.bdqn.pojo.User;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * UserServiceImpl
 *
 * @author LILIBO
 * @since 2021-11-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param usrName
     * @param usrPassword
     * @return
     */
    @Override
    public User login(String usrName, String usrPassword) {
        if (StringUtils.isEmpty(usrName) || StringUtils.isEmpty(usrPassword)) {
            return null;
        }
        String enPassword = encryptPassword(usrPassword);
        return userMapper.getUser(new User(usrName, enPassword));
    }

    /**
     * 使用Shiro中的加密方式
     *
     * @param plaintextPassword
     * @return
     * @throws IllegalArgumentException
     */
    public String encryptPassword(Object plaintextPassword) throws IllegalArgumentException {
        String salt = "czkt";
        Md5Hash md5Hash = new Md5Hash(plaintextPassword, salt, 2);
        return md5Hash.toString();
    }

    /**
     * 保存或修改用户（如果有主键ID则修改，没有则保存）
     *
     * @param user
     */
    @Override
    public boolean saveUser(User user) {
        return super.saveOrUpdate(user); // 使用MyBatis-Plus提供的方法
    }

    /**
     * 根据ID删除用户
     *
     * @param usrId
     */
    @Override
    public boolean deleteUser(Long usrId) {
        return super.removeById(usrId);
    }

    /**
     * 根据ID获得单个用户对象
     *
     * @param usrId
     * @return
     */
    @Override
    public User getUser(Long usrId) {
        return super.getById(usrId);
    }

    /**
     * 分页获得用户数据
     *
     * @param usrName
     * @param roleId
     * @param page
     * @return
     */
    @Override
    public IPage<User> findUsers(String usrName, Long roleId, Page page) {
        return super.getPage(page, new User(usrName, roleId));
    }

    @Override
    public User user(Long usrId) {
        return super.getById(usrId);
    }


}
